﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;

using HA.Data;

namespace HA.ModFlow.Controls.Windows
{
    /// <summary>
    /// winImportTxtCsvFile.xaml 的交互逻辑
    /// </summary>
    public partial class winImportTxtCsvFile : Window
    {
        public winImportTxtCsvFile(Project project)
        {
            this._project = project;



            InitializeComponent();
            this.chkSpace.Click += new RoutedEventHandler(chkSpace_Click);
            this.chkComma.Click += new RoutedEventHandler(chkSpace_Click);
            this.chkOther.Click += new RoutedEventHandler(chkSpace_Click);
            this.chkSemicolon.Click += new RoutedEventHandler(chkSpace_Click);
            this.chkTab.Click += new RoutedEventHandler(chkSpace_Click);
            this.dgrid.IsReadOnly = true;

            this.txtInvalidData.DataContext = this;
            this.txtBoxXOffSet.DataContext = this;
            this.txtBoxYOffSet.DataContext = this;
        }

        #region 属性字段

        double _xOffSet = 0;
        /// <summary>
        /// x方向上偏移量
        /// </summary>
        public double XOffSet
        {
            get { return _xOffSet; }
            set { _xOffSet = value; }
        }

        double _yOffSet = 0;
        /// <summary>
        /// y方向上偏移量
        /// </summary>
        public double YOffSet
        {
            get { return _yOffSet; }
            set { _yOffSet = value; }
        }

        double _zOffSet = 0;
        /// <summary>
        /// z方向上偏移量
        /// </summary>
        public double ZOffSet
        {
            get { return _zOffSet; }
            set { _zOffSet = value; }
        }

        Project _project;

        ImportWizardType _importDataType = ImportWizardType.SCATTER2D;
        /// <summary>
        /// 标记导入的数据类型
        /// </summary>
        public ImportWizardType ImportDataType
        {
            get { return _importDataType; }
        }

        Scatter2D _scatter2D;
        /// <summary>
        /// 
        /// </summary>
        public Scatter2D Scatter2D
        {
            get { return _scatter2D; }
        }

        bool _isDataValid = true;
        /// <summary>
        /// 标志数据是否有效可用
        /// </summary>
        public bool IsDataValid
        {
            get { return _isDataValid; }
        }

        static ComboBox ComboBoxScatter2D
        {
            get
            {
                ComboBox cb = new ComboBox();

                cb.Width = 100;

                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = "无映射";
                cbi.Name = "none";
                cb.Items.Add(cbi);

                cbi = new ComboBoxItem();
                cbi.Content = "X坐标";
                cbi.Name = "xCoordinate";
                cb.Items.Add(cbi);

                cbi = new ComboBoxItem();
                cbi.Content = "Y坐标";
                cbi.Name = "yCoordinate";
                cb.Items.Add(cbi);

                cbi = new ComboBoxItem();
                cbi.Content = "数据";
                cbi.Name = "dataSet";
                cbi.IsSelected = true;
                cb.Items.Add(cbi);

                //cbi = new ComboBoxItem();
                //cbi.Content = "Label";
                //cbi.Name = "label";
                //cb.Items.Add(cbi);

                return cb;
            }
        }

        static ComboBox ComboBoxScatter3D
        {
            get
            {
                ComboBox cb = new ComboBox();

                cb.Width = 100;

                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = "无映射";
                cbi.Name = "none";
                cb.Items.Add(cbi);

                cbi = new ComboBoxItem();
                cbi.Content = "X坐标";
                cbi.Name = "xCoordinate";
                cb.Items.Add(cbi);

                cbi = new ComboBoxItem();
                cbi.Content = "Y坐标";
                cbi.Name = "yCoordinate";
                cb.Items.Add(cbi);

                cbi = new ComboBoxItem();
                cbi.Content = "Z坐标";
                cbi.Name = "zCoordinate";
                cb.Items.Add(cbi);

                cbi = new ComboBoxItem();
                cbi.Content = "数据";
                cbi.Name = "dataSet";
                cbi.IsSelected = true;
                cb.Items.Add(cbi);

                //cbi = new ComboBoxItem();
                //cbi.Content = "Label";
                //cbi.Name = "label";
                //cb.Items.Add(cbi);

                return cb;
            }
        }

        /// <summary>
        /// 所有行中最多列的列数
        /// </summary>
        int columnsMaxNum = int.MinValue;

        /// <summary>
        /// 所有行中最少列的列数
        /// </summary>
        int columnsMinNum = int.MaxValue;

        private string mPath = "";

        int startImportRow = 1;

        private int StartImportRow
        {
            get { return startImportRow; }
            set { startImportRow = value; }
        }

        double _invalidData = -999.0;

        public double InvalidData
        {
            get { return _invalidData; }
            set { _invalidData = value; }
        }


        #endregion


        #region 触发的事件函数
        

        void chkSpace_Click(object sender, RoutedEventArgs e)
        {
            if (this.chkOther.IsChecked.Value)
            {
                this.txtOther.IsEnabled = true;
            }
            else
            {
                this.txtOther.IsEnabled = false;
                this.txtOther.Text = "";
            }
            ReadTxt();

        }

        
        private void btnImportFile_Click(object sender, RoutedEventArgs e)
        {
            //this.dgrid.ColumnWidth = 100;

            Microsoft.Win32.OpenFileDialog open = new Microsoft.Win32.OpenFileDialog();
            open.Filter = "as.txt|*.txt|csv.csv|*.csv";
            //open.Filter = "as.csv|*.csv";
            if (open.ShowDialog().Value)
            {
                

                mPath = open.FileName;
                string extension = System.IO.Path.GetExtension(mPath).ToLower();

                this.txtBoxName.Text = System.IO.Path.GetFileNameWithoutExtension(mPath);

                System.Data.DataTable dt = new System.Data.DataTable();

                if (extension == ".txt" || extension == ".csv")  //读取文本文件和excel文件用同一个方法就行
                {
                    bool b= this.ReadTxt();  //读取文本文件
                    this.dgrid.DataContext = this;

                    if (b == false)
                    {
                        MessageBox.Show("文件读取失败，请确保文件处于关闭状态！");
                        return;
                    }

                    columnsMaxNum = int.MinValue;

                    columnsMinNum = int.MaxValue;

                    foreach (string[] row in this.arryString)
                    {
                        if (columnsMaxNum < row.Length)
                        {
                            columnsMaxNum = row.Length;
                        }
                        if (columnsMinNum > row.Length)
                            columnsMinNum = row.Length;
                    }

                    if (columnsMaxNum < columnsMinNum)
                        return;

                    for (int i = 0; i < columnsMaxNum; i++)
                    {
                        System.Data.DataColumn column = new System.Data.DataColumn("列" + (i + 1));
                        column.Caption = " ";
                        dt.Columns.Add(column);
                    }

                    if (chkHeaderRow.IsChecked.Value)
                    {
                        Dictionary<int, string> dataPosition = new Dictionary<int, string>();

                        for (int i = 0; i < this.arryString[0].Length; i++)
                        {
                            switch (this.arryString[0][i].Trim().ToLower())
                            {
                                case "x":

                                    if (!dataPosition.ContainsValue("x"))
                                        dataPosition.Add(i, "x");

                                    break;
                                case "y":

                                    if (!dataPosition.ContainsValue("y"))
                                        dataPosition.Add(i, "y");

                                    break;

                                case "label":
                                    if (!dataPosition.ContainsValue("label"))
                                        dataPosition.Add(i, "label");

                                    break;

                                case "id":
                                    if (!dataPosition.ContainsValue("id"))
                                        dataPosition.Add(i, "id");

                                    break;

                                default:
                                    break;
                            }
                        }

                        SetListBoxSpecializeDataType(dataPosition);
                    }
                    else
                        SetListBoxSpecializeDataType();
                    

                    foreach (string[] line in this.arryString)
                    {
                        System.Data.DataRow row = dt.NewRow();
                        row.ItemArray = line;
                        dt.Rows.Add(row);
                    }

                }
                else if (extension == ".csv")  //读取excel文件
                {
                    arryString = ReadCSV(open.FileName);
                }
                this.dgrid.ItemsSource = dt.DefaultView;
                //this.dgrid.ItemsSource = this.ArryString.ToArray();
                //this.dgrid.AutoGenerateColumns = false;

            }
        }


        private void comboBoxDataType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (comboBoxDataType.SelectedIndex)
            {
                case 0:
                    this._importDataType = ImportWizardType.SCATTER2D;
                    SetListBoxSpecializeDataType();
                    break;

                case 1:
                    this._importDataType = ImportWizardType.SCATTER3D;
                    SetListBoxSpecializeDataType();
                    break;

                default:
                    break;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }





        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            switch (this._importDataType)
            {
                case ImportWizardType.SCATTER2D:
                    this._scatter2D = this._project.Scatter2dData.CreateNew();
                    if (this.txtBoxName.Text.Trim() != null && this.txtBoxName.Text.Trim() != "")
                        _scatter2D.Name = this.txtBoxName.Text.Trim();

                    List<int> xPosition = new List<int>();
                    List<int> yPosition = new List<int>();
                    List<int> dataSetPosition = new List<int>();

                    if (this.lstBoxDataTypes.Items.Count < 3)
                    {
                        MessageBox.Show("列数不够！");
                        return;
                    }
                    for (int i = 0; i < this.lstBoxDataTypes.Items.Count; i++)
                    {
                        StackPanel sp = (StackPanel)this.lstBoxDataTypes.Items[i];

                        switch (((ComboBox)sp.Children[1]).SelectedIndex)
                        {
                            case 0://Not Mapped

                                break;

                            case 1://x
                                xPosition.Add(i);
                                break;

                            case 2://y
                                yPosition.Add(i);
                                break;

                            case 3://dataSet
                                dataSetPosition.Add(i);
                                break;

                            case 4://label

                                break;

                            default:
                                break;
                        }
                    }

                    if (xPosition.Count != 1 || yPosition.Count != 1 || dataSetPosition.Count <= 0)
                    {
                        MessageBox.Show("指定的列类型不正确，请重新指定！");
                        return;
                    }

                    try
                    {
                        int startimportrow = 0;
                        if (this.chkHeaderRow.IsChecked.Value)
                        {
                            for (int j = 0; j < dataSetPosition.Count; j++)
                            {
                                _scatter2D.ValueNames.Add(this.arryString[0][dataSetPosition[j]]);
                            }
                            startimportrow = 1;
                        }
                        else
                        {
                            for (int j = 0; j < dataSetPosition.Count; j++)
                            {
                                _scatter2D.ValueNames.Add("data" + (j + 1));
                            }
                        }

                        if (!chkInvalidData.IsChecked.Value)
                        {
                            for (int i = startimportrow; i < this.arryString.Count; i++)
                            {
                                string[] str = this.arryString[i];
                                List<double> values = new List<double>();
                                for (int j = 0; j < dataSetPosition.Count; j++)
                                {
                                    values.Add(Convert.ToDouble(str[dataSetPosition[j]]));
                                }

                                ScatterPoint sp = new ScatterPoint(_scatter2D.GetNextScatterPointId(), values, Convert.ToDouble(str[xPosition[0]]) + _xOffSet, Convert.ToDouble(str[yPosition[0]]) + _yOffSet);
                                
                                _scatter2D.DataSet.Add(sp);
                            }
                        }
                        else
                        {
                            for (int i = startimportrow; i < this.arryString.Count; i++)
                            {
                                string[] str = this.arryString[i];
                                List<double> values = new List<double>();
                                for (int j = 0; j < dataSetPosition.Count; j++)
                                {
                                    values.Add(Convert.ToDouble(str[dataSetPosition[j]]));
                                }
                                if (values.Contains(_invalidData))
                                    continue;

                                ScatterPoint sp = new ScatterPoint(_scatter2D.GetNextScatterPointId(), values, Convert.ToDouble(str[xPosition[0]]) + _xOffSet, Convert.ToDouble(str[yPosition[0]]) + _yOffSet);
                                
                                _scatter2D.DataSet.Add(sp);
                            }
                        }
                    }
                    catch
                    {
                        MessageBox.Show("数据格式错误，请检查数据格式是否正确！");
                        return;
                    }

                    break;

                case ImportWizardType.SCATTER3D:
                    this._project.Scatter3dData.CreateNew();


                    break;

                default:
                    break;
            }


            this.DialogResult = true;
            this.Close();
        }

        #endregion


        #region 辅助函数

        bool SetListBoxSpecializeDataType(Dictionary<int, string> dataPosition = null)
        {
            if (this.lstBoxDataTypes == null)
                return false;
            switch (this._importDataType)
            {
                case ImportWizardType.SCATTER2D:

                    this.lstBoxDataTypes.Items.Clear();

                    if (dataPosition == null)
                    {
                        for (int i = 0; i < columnsMaxNum; i++)
                        {
                            StackPanel sp = new StackPanel();
                            sp.Orientation = Orientation.Horizontal;

                            Label lab = new Label();
                            lab.Content = "第" + (i + 1) + "列:";
                            sp.Children.Add(lab);
                            sp.Children.Add(ComboBoxScatter2D);

                            this.lstBoxDataTypes.Items.Add(sp);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < columnsMaxNum; i++)
                        {
                            StackPanel sp = new StackPanel();
                            sp.Orientation = Orientation.Horizontal;

                            Label lab = new Label();
                            lab.Content = "第" + (i + 1) + "列:";
                            sp.Children.Add(lab);

                            ComboBox cb = ComboBoxScatter2D;
                            if(dataPosition.ContainsKey(i))
                                switch (dataPosition[i])
                                {
                                    case "x":
                                        cb.SelectedIndex = 1;
                                        break;

                                    case "y":
                                        cb.SelectedIndex = 2;
                                        break;

                                    case "label":
                                        cb.SelectedIndex = 0;
                                        break;

                                    case "id":
                                        cb.SelectedIndex = 0;
                                        break;

                                    default:
                                        break;
                                }

                            sp.Children.Add(cb);

                            this.lstBoxDataTypes.Items.Add(sp);
                        }
                    }

                    break;
                case ImportWizardType.SCATTER3D:

                    this.lstBoxDataTypes.Items.Clear();

                    for (int i = 0; i < columnsMaxNum; i++)
                    {
                        StackPanel sp = new StackPanel();
                        sp.Orientation = Orientation.Horizontal;

                        Label lab = new Label();
                        lab.Content = "第" + (i + 1) + "列:";
                        sp.Children.Add(lab);
                        sp.Children.Add(ComboBoxScatter3D);

                        this.lstBoxDataTypes.Items.Add(sp);
                    }

                    break;
                default:
                    break;
            }



            return true;
        }



        /// <summary>
        /// 读取CSV格式文件
        /// </summary>
        /// <param name="filePathName"></param>
        /// <returns></returns>
        public static List<String[]> ReadCSV(string filePathName)
        {
            List<String[]> ls = new List<String[]>();
            StreamReader fileReader = new StreamReader(filePathName);
            string strLine = "";
            while (strLine != null)
            {
                strLine = fileReader.ReadLine();
                if (strLine != null && strLine.Length > 0)
                {
                    ls.Add(strLine.Split(','));
                }
            }
            fileReader.Close();
            return ls;
        }

        private List<string[]> arryString = new List<string[]>();

        public List<string[]> ArryString
        {
            get { return arryString; }
        }

        /// <summary>
        /// 读取txt文件，刘改
        /// </summary>
        private bool ReadTxt()
        {
            List<char> split = new List<char>();
            if (this.chkSpace.IsChecked.Value)
            {
                split.Add(' ');
            }
            if (this.chkTab.IsChecked.Value)
            {
                split.Add('\t');
            }
            if (this.chkSemicolon.IsChecked.Value)
            {
                split.Add(';');
            }
            if (this.chkComma.IsChecked.Value)
            {
                split.Add(',');
            }
            if (this.chkOther.IsChecked.Value)
            {
                split.AddRange(this.txtOther.Text.ToCharArray());
            }

            this.arryString = HA.Data.TxtCsvFileReader.ReadTxtfile(mPath, split.ToArray());

            if (this.arryString == null) return false;
            else
            {
                return true;
            }

        }

        ///// <summary>
        ///// 得到文件的字符串数据,刘注销，读取txt文件用上面那个方法
        ///// </summary>
        ///// <param name="FileName"></param>
        ///// <returns></returns>
        //public List <string []> GetResultStr(string FileName, string str)
        //{
        //    List<string[]> arryListData = new List<string[]>();
        //    arryListData.Clear();
        //    if (System.IO.File.Exists(FileName))
        //    {
        //        try
        //        {
        //            using (StreamReader mReader = new StreamReader(FileName))
        //            {
        //                while (mReader.Peek() >= 0)
        //                {
        //                    string mStr = mReader.ReadLine();

        //                    //==============================
        //                    int P = HAUtil.FileImporter.GetStringNumber(mStr, str);
        //                    string[] mystr = new string[P];
        //                    for (int k = 0; k < mystr.Length; k++)
        //                    {
        //                        mystr[k] = HAUtil.FileImporter.GetString(mStr, (k + 1),  str);
        //                    }
        //                    arryListData.Add(mystr);



        //                    //=============================
        //                    //Data da = new Data();
        //                    //int i = 0;
        //                    //da.Name = GetString(mStr, (i + 1), str);
        //                    //da.X = GetString(mStr, (i + 2), str);
        //                    //da.Y = GetString(mStr, (i + 3), str);
        //                    //da.Z = GetString(mStr, (i + 4), str);
        //                    //da.Material = GetString(mStr, (i + 5), str);

        //                    //this.mArryData.Add(da);
        //                }
        //            }
        //        }
        //        catch
        //        {
        //            return null ;
        //        }

        //    }
        //    else
        //    {
        //        return null;
        //    }
        //    return arryListData;
        //}

        #endregion


    }
}
